"use client";

import React from 'react';
import MarkdownViewer from '~/components/markdown-viewer';
import { useLanguage } from '~/lib/LanguageContext';
import 'prismjs/themes/prism-okaidia.css';
import 'prismjs/components/prism-groovy';
import Link from 'next/link';

export default function JenkinsIntegrationPage() {
  const { language } = useLanguage();
  
  const contentEn = `
# Jenkins Integration for CodeMariner

This guide will help you integrate CodeMariner with Jenkins CI/CD pipelines.

## Prerequisites

- Jenkins server installed and running
- Git plugin for Jenkins
- Node.js installed on Jenkins server
- Access to your CodeMariner repository

## Steps to Integrate

### 1. Create a Jenkinsfile

Create a \`Jenkinsfile\` in the root of your repository:

\`\`\`groovy
// Jenkinsfile - Pipeline Script for CodeMariner
pipeline {
    agent {
        node {
            label 'node' // Use a node with Node.js installed
        }
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm // This checks out your repository
            }
        }
        
        stage('Install Dependencies') {
            steps {
                sh 'pnpm install' // Install npm packages with pnpm
            }
        }
        
        stage('Build Frontend') {
            steps {
                sh 'pnpm build' // Build Next.js application
            }
        }
        
        stage('Test') {
            steps {
                sh 'pnpm test' // Run test suite
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main' // Only deploy from main branch
            }
            steps {
                sh 'pnpm deploy' // Adjust based on your deployment script
            }
        }
    }
    
    post {
        always {
            cleanWs() // Clean workspace after pipeline execution
        }
    }
}
\`\`\`

### 2. Create a Jenkins Pipeline Job

1. In Jenkins, create a new Pipeline job
2. Configure the job to use your Git repository
3. Set it to use the Jenkinsfile from your repository

### 3. Configure Backend Deployment

For the FastAPI backend:

\`\`\`groovy
// Backend Deployment Stage Configuration
stage('Deploy Backend') {
    when {
        branch 'main' // Only deploy from main branch
    }
    steps {
        dir('backend') { // Change to backend directory
            sh 'pip install -r requirements.txt' // Install Python dependencies
            sh 'docker build -t gitdiagram-backend .' // Build Docker image
            sh 'docker push your-registry/gitdiagram-backend:latest' // Push to registry
            // Deploy to your EC2 instance
            sh 'ssh user@your-ec2-instance "./deploy-backend.sh"'
        }
    }
}
\`\`\`

### 4. Set Up Database Migrations

Include database migration in your pipeline:

\`\`\`groovy
// Database Migration Stage Configuration
stage('Database Migration') {
    when {
        branch 'main' // Only run migrations from main branch
    }
    steps {
        sh 'pnpm migrate' // Execute database migrations
    }
}
\`\`\`

### 5. Configure Webhooks

Set up webhooks from GitHub to Jenkins to trigger builds automatically on code changes.

## Best Practices

- Use environment variables for sensitive information
- Implement proper error handling and notifications
- Set up parallel testing for faster builds
- Add code quality checks using tools like ESLint

## Example Docker Deployment Script

Create a \`deploy-backend.sh\` script on your EC2 instance:

\`\`\`bash
#!/bin/bash
# EC2 Deployment Script for CodeMariner Backend

# Pull the latest image
docker pull your-registry/gitdiagram-backend:latest

# Stop and remove existing container if it exists
docker stop gitdiagram-backend || true
docker rm gitdiagram-backend || true

# Run new container
docker run -d --name gitdiagram-backend \\
  -p 8000:8000 \\
  -e DATABASE_URL=\${DATABASE_URL} \\
  -e API_KEY=\${API_KEY} \\
  your-registry/gitdiagram-backend:latest
\`\`\`

## Troubleshooting

If you encounter issues with your Jenkins integration, check:

- Jenkins logs for detailed error messages
- Network connectivity between Jenkins and your deployment targets
- Permissions for Jenkins to access your repositories and deployment targets
`;

  const contentZh = `
# CodeMariner的Jenkins集成

本指南将帮助您将CodeMariner与Jenkins CI/CD流水线集成。

## 前提条件

- Jenkins服务器（已安装和配置）
- 访问您的CodeMariner仓库的权限

## 集成步骤

### 1. 创建Jenkinsfile

在您仓库的根目录创建一个\`Jenkinsfile\`：

\`\`\`groovy
// Jenkinsfile - CodeMariner的流水线脚本
pipeline {
    agent {
        node {
            label 'node' // 使用安装了Node.js的节点
        }
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm // 检出您的代码仓库
            }
        }
        
        stage('Install Dependencies') {
            steps {
                sh 'pnpm install' // 使用pnpm安装npm包
            }
        }
        
        stage('Build Frontend') {
            steps {
                sh 'pnpm build' // 构建Next.js应用
            }
        }
        
        stage('Test') {
            steps {
                sh 'pnpm test' // 运行测试套件
            }
        }
        
        stage('Deploy') {
            when {
                branch 'main' // 仅从main分支部署
            }
            steps {
                sh 'pnpm deploy' // 根据您的部署脚本调整
            }
        }
    }
    
    post {
        always {
            cleanWs() // 流水线执行后清理工作区
        }
    }
}
\`\`\`

### 2. 创建Jenkins流水线作业

1. 在Jenkins中，创建一个新的流水线作业
2. 配置作业使用您的Git仓库
3. 设置使用仓库中的Jenkinsfile

### 3. 配置后端部署

对于FastAPI后端：

\`\`\`groovy
// 后端部署阶段配置
stage('Deploy Backend') {
    when {
        branch 'main' // 仅从main分支部署
    }
    steps {
        dir('backend') { // 切换到后端目录
            sh 'pip install -r requirements.txt' // 安装Python依赖
            sh 'docker build -t gitdiagram-backend .' // 构建Docker镜像
            sh 'docker push your-registry/gitdiagram-backend:latest' // 推送到镜像仓库
            // 部署到您的EC2实例
            sh 'ssh user@your-ec2-instance "./deploy-backend.sh"'
        }
    }
}
\`\`\`

### 4. 设置数据库迁移

在您的流水线中包含数据库迁移：

\`\`\`groovy
// 数据库迁移阶段配置
stage('Database Migration') {
    when {
        branch 'main' // 仅从main分支运行迁移
    }
    steps {
        sh 'pnpm migrate' // 执行数据库迁移
    }
}
\`\`\`

### 5. 配置Webhooks

设置从GitHub到Jenkins的webhooks，以在代码更改时自动触发构建。

## 最佳实践

- 使用环境变量存储敏感信息
- 实施适当的错误处理和通知
- 设置并行测试以加快构建速度
- 使用ESLint等工具添加代码质量检查

## 示例Docker部署脚本

在您的EC2实例上创建一个\`deploy-backend.sh\`脚本：

\`\`\`bash
#!/bin/bash
# EC2上CodeMariner后端的部署脚本

# 拉取最新镜像
docker pull your-registry/gitdiagram-backend:latest

# 如果存在，停止并移除现有容器
docker stop gitdiagram-backend || true
docker rm gitdiagram-backend || true

# 运行新容器
docker run -d --name gitdiagram-backend \\
  -p 8000:8000 \\
  -e DATABASE_URL=\${DATABASE_URL} \\
  -e API_KEY=\${API_KEY} \\
  your-registry/gitdiagram-backend:latest
\`\`\`

## 故障排除

如果您在Jenkins集成中遇到问题，请检查：

- Jenkins日志以获取详细的错误消息
- Jenkins与您的部署目标之间的网络连接
- Jenkins访问您的存储库和部署目标的权限
`;

  return (
    <div className="relative">
      <div className="absolute top-4 left-4">
        <Link href="/" className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 transition-colors">
          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="mr-2">
            <path d="M15 18l-6-6 6-6" />
          </svg>
          {language === 'zh' ? '返回首页' : 'Back to Home'}
        </Link>
      </div>
      
      <div className="container mx-auto max-w-4xl px-4 py-8">
        <style jsx global>{`
          /* 为代码块容器添加相对定位 */
          pre[class*="language-"] {
            position: relative;
            margin: 1.5em 0 !important;
            padding-top: 2.5rem !important;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
          }
          
          /* 使用伪元素为代码块添加语言标签 */
          pre.language-groovy::before {
            content: "Groovy";
            position: absolute;
            top: 0;
            right: 0;
            background-color: rgba(66, 153, 225, 0.8);
            color: white;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            border-bottom-left-radius: 0.5rem;
            z-index: 10;
          }
          
          pre.language-bash::before {
            content: "Bash";
            position: absolute;
            top: 0;
            right: 0;
            background-color: rgba(72, 187, 120, 0.8);
            color: white;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            border-bottom-left-radius: 0.5rem;
            z-index: 10;
          }
        `}</style>
        <MarkdownViewer 
          content={language === 'zh' ? contentZh : contentEn} 
          className="prose prose-slate dark:prose-invert max-w-none"
        />
      </div>
    </div>
  );
} 